import React from 'react'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Modal, Button, DatePicker, message } from 'antd'
import { CalendarOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons'
import moment from 'moment'
import style from './Index.module.less'
import TimePicker from '../TimePicker/Index'

class Index extends Component {
  state = {
    datepickerOpen: false,
    today: moment(this.formatDate(moment())),
    selectedDate: moment(this.formatDate(moment())),
    roomList: [],
    selectedRoom: null,
    beginTime: null,
    endTime: null,
    bookedInfo: null
  }

  dateRef = React.createRef()

  setBeginTime (v) {
    this.setState({
      beginTime: v
    })
  }

  setEndTime (v) {
    this.setState({
      endTime: v
    })
  }

  // 获取案件已预约庭室信息
  getBookedInfo () {
    const date = Math.floor(moment(this.formatDate(this.state.selectedDate)) / 1000)
    const hide = message.loading('获取全部已预约庭室信息中', 120)
    this.$get('/api/xapc/hearingroombook', {
      begin_datetime: date,
      end_datetime: date + 86400
    }).then(res => {
      hide()
      if (res.status === 1) {
        this.setState({
          bookedInfo: res.data
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 获取庭室列表
  getRoomList () {
    this.$get('/api/xapc/hearingroom')
      .then(res => {
        if (res.status === 1) {
          this.setState({
            roomList: res.data
          })
        } else {
          message.warning(res.message)
        }
      })
  }

  // 初始化数据
  initParams () {
    const { roomList } = this.state
    const { value: v } = this.props
    if (!v) {
      const today = moment().format('YYYY-MM-DD')
      this.setState({
        selectedRoom: null,
        selectedDate: moment(today),
        beginTime: null,
        endTime: null
      })
      return false
    }
    const data = {}
    // 如果庭室名称获取庭室id相同时，设置选中庭室
    for (let i = 0; i < roomList.length; i++) {
      const r = roomList[i]
      if (r.id === v.room_id || r.name === v.room_name) {
        data.selectedRoom = r
        break
      }
    }

    if (v.date) {
      data.selectedDate = moment(v.date)
    }

    if (v.start_time && v.end_time && v.date) {
      data.beginTime = moment(v.date + ' ' + v.start_time)
      data.endTime = moment(v.date + ' ' + v.end_time)
    }
    this.setState(data, () => {
      this.getBookedInfo()
    })
  }

  formatDate (date) {
    if (date instanceof moment) {
      return date.format('YYYY-MM-DD')
    }
  }

  changeDate (v) {
    this.setState({ datepickerOpen: false, selectedDate: v }, () => {
      this.getBookedInfo()
    })
  }

  prevDay () {
    const d = moment(this.state.selectedDate)
    d.subtract(1, 'd')
    if (this.getDisabledDate(d)) {
      return false
    }
    this.changeDate(d)
  }

  nextDay () {
    const d = moment(this.state.selectedDate)
    d.add(1, 'd')
    this.changeDate(d)
  }

  getDisabledDate (v) {
    return v < moment(moment().format('YYYY-MM-DD'))
  }

  // 设置当前选中庭室和日期
  selectdRoomAndDate (room, date) {
    if (moment(date) < this.state.today) {
      return false
    }
    this.setState({
      selectedRoom: room
    })
  }

  // 重置选中参数
  resetParams () {
    this.setState({
      selectedDate: moment(moment().format('YYYY-MM-DD')),
      selectedRoom: null,
      beginTime: null,
      endTime: null
    })
  }

  // 取消回调事件
  cancelHandle () {
    this.props.hide()
    this.resetParams()
  }

  // 确定回调事件
  okHandle () {
    const { selectedRoom, selectedDate, beginTime, endTime } = this.state
    if (!selectedRoom) {
      return message.warning('请选择庭室')
    }
    if (!selectedDate) {
      return message.warning('请选择开庭日期')
    }
    if (!beginTime) {
      return message.warning('请选择开始时间')
    }
    if (!endTime) {
      return message.warning('请选择结束时间')
    }
    const year = moment().format('YYYY-MM-DD')
    const beginTimeValue = moment(`${year} ${beginTime.format('HH:mm')}`).valueOf()
    const endTimeValue = moment(`${year} ${endTime.format('HH:mm')}`).valueOf()
    if (beginTimeValue > endTimeValue) {
      return message.warning('结束时间不能早于开始时间')
    }
    if (beginTimeValue === endTimeValue) {
      return message.warning('结束时间不能等于开始时间')
    }
    this.props.onChange({
      room_name: selectedRoom.name,
      room_id: selectedRoom.id,
      date: selectedDate.format('YYYY-MM-DD'),
      start_time: beginTime.format('HH:mm'),
      end_time: endTime.format('HH:mm')
    })
    this.resetParams()
  }

  // 返回禁用的分钟数
  getDisabledMinutes () {
    const arr = []
    for (let i = 0; i <= 59; i++) {
      if (i % 15 !== 0) {
        arr.push(i)
      }
    }
    return arr
  }

  componentDidUpdate (prev) {
    const { visible } = this.props
    if (visible && !prev.visible) {
      this.initParams()
    }
  }

  componentDidMount () {
    this.getRoomList()
    this.initParams()
  }

  renderFooter () {
    // const { selectedRoom, selectedDate } = this.state
    return (
      <div className={style.footer}>
        <span className={style['footer-info']}>
          {/* <span className={style['footer-info-cell']}>庭室：{selectedRoom ? selectedRoom.name : '暂无'}</span>
          <span className={style['footer-info-cell']}>开庭日期：{selectedDate.format('YYYY-MM-DD') || '暂无'}</span> */}
          <span className={style['footer-info-cell']}>
            <span className={style.require}>开始时间：</span>
            <TimePicker value={this.state.beginTime} disabledHours={() => [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23]} disabledMinutes={() => this.getDisabledMinutes()} onChange={v => this.setBeginTime(v)} />
          </span>
          <span className={style['footer-info-cell']}>
            <span className={style.require}>结束时间：</span>
            <TimePicker value={this.state.endTime} disabledHours={() => [0, 1, 2, 3, 4, 5, 6, 7, 21, 22, 23]} disabledMinutes={() => this.getDisabledMinutes()} onChange={v => this.setEndTime(v)} />
          </span>
        </span>
        <span className={style['footer-btns']}>
          <Button onClick={() => this.cancelHandle()}>取消</Button>
          <Button type='primary' onClick={() => this.okHandle()}>确定</Button>
        </span>
      </div>
    )
  }

  // 渲染预约信息块
  renderBookInfoBlock (li) {
    const { selectedRoom } = this.state
    const arr = [style['room-cell']]
    if (selectedRoom && selectedRoom.id === li.id) {
      arr.push(style.active)
    }
    return (
      <div key={li.id} className={arr.join(' ')} onClick={() => this.selectdRoomAndDate(li)}>
        <div className={style['room-title']}>{li.name}{li.remark}</div>
        <div className={style['room-time-list']}>
          {this.renderBookRoomDays(li)}
        </div>
      </div>
    )
  }

  // 渲染庭室预约情况
  renderBookRoomDays (li) {
    let roomBooked = {}
    if (this.state.bookedInfo) {
      roomBooked = this.state.bookedInfo[li.id] || {}
    }
    const mDate = this.formatDate(this.state.selectedDate)
    const bookedList = roomBooked[mDate] || []
    return bookedList.map((li, i) => {
      return <div key={i}>{li.time}</div>
    })
  }

  // 渲染庭室列表
  renderRoomList () {
    return (
      <div className={style['room-container']}>
        <div className={style['room-list']}>
          {this.state.roomList.map(li => {
            return this.renderBookInfoBlock(li)
          })}
        </div>
      </div>
    )
  }

  render () {
    const prevClass = [style['header-btn']]
    if (this.formatDate(this.state.selectedDate) === this.formatDate(this.state.today)) {
      prevClass.push(style.disable)
    }
    return (
      <Modal
        title='选择仲裁庭和开庭时间'
        width={1050}
        open={this.props.visible}
        destroyOnClose
        maskClosable={false}
        onCancel={() => this.cancelHandle()}
        footer={this.renderFooter()}
      >
        <div className={style.header}>
          <label className={style['header-date']}>
            <span className={style['header-date-text']}>{this.formatDate(this.state.selectedDate)}</span>
            <span className={style.datepicker}>
              <DatePicker value={this.state.selectedDate} ref={this.dateRef} inputReadOnly disabledDate={v => this.getDisabledDate(v)} open={this.state.datepickerOpen} onChange={v => this.changeDate(v)} onFocus={() => this.setState({ datepickerOpen: true })} onBlur={() => this.setState({ datepickerOpen: false })} />
            </span>
            <CalendarOutlined className={style['calendar-icon']} />
          </label>
          <div className={style['header-btns']}>
            <span className={prevClass.join(' ')} onClick={() => this.prevDay()}><LeftOutlined /></span>
            <span className={style['header-btn']} onClick={() => this.nextDay()}><RightOutlined /></span>
          </div>
        </div>
        {this.renderRoomList()}
      </Modal>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(Index)

Index.proptypes = {
  visible: PropTypes.bool,
  onChange: PropTypes.func,
  hide: PropTypes.func,
  value: PropTypes.object,
  caseDetail: PropTypes.object
}

Index.defaultProps = {
  visible: false,
  onChange: () => {},
  hide: () => {},
  value: {
    room_name: '',
    room_id: '',
    date: '',
    start_time: '',
    end_time: ''
  },
  caseDetail: {}
}
